import { Element,render,setAttr } from './element';
// 从外到内，从左到右  
let allPatches;
let index = 0;

function patch(node,patches) {
    allPatches = patches;
    walk(node);
}

function walk(node) {
    // 当前节点要做的补丁  
    let current = allPatches[index++];
    // console.log(current,index)
    let childNodes = node.childNodes;
    // 深度优先 先序遍历
    childNodes.forEach(child => walk(child));
    if(current) {
        doPatch(node,current);
    }
}

function doPatch(node,patches) {
    // DOM 编程
    patches.forEach(patch => {
        switch(patch.type) {
            case 'ATTRS':
                for(let key in patch.attrs){
                    let value = patch.attrs[key];
                    if(value) {
                        setAttr(node,key,value);
                    } else {
                        node.removeAttribute(key);
                    }
                }
            break;
            case 'REPLACE':
                let newNode = (path.newNode instanceof Element)
                    ? render(path.newNode)
                    : document.createTextNode(path.newNode);
                node.parentNode.replaceChild(newNode,node);
            break;
            case 'TEXT':
                node.textContent = patch.text;
            break;
            case 'REMOVE':
                node.parentNode.replaceChild(node);
            break;
            default:
                break;
        }
    })
}

export default patch;